package com.mocha.base.aop;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * 压测： 300线程 1秒 循环；  tomcat cpu占用最高；
 * tomact cpu 再 70%
 * undertow cpu 再 50%
 * logback：日志耗cpu;
 */
@Aspect
@Slf4j
public class OperationLogsAspect {

    @Pointcut("@annotation(com.mocha.base.aop.OperationLog)")
    public void pointcut() {
    }

    @Around(value = "pointcut()")
    public Object operationLogController(ProceedingJoinPoint point) throws Throwable {

        log.info("================== START ==============");
        long startTime = System.currentTimeMillis();
        String clsName = point.getTarget().getClass().getSimpleName();
        String methodName = point.getSignature().getName();
        log.info("Request【{} {}】, parameter: {}.", clsName, methodName, getParam(point));
        try {
            return point.proceed();
        } finally {
            long endTime = System.currentTimeMillis();
            log.info("Total time: {} {}", (endTime - startTime), "ms");
            log.info("================== END ==============");
        }
    }


    private String getParam(ProceedingJoinPoint point) {
        MethodSignature methodSignature = (MethodSignature) point.getSignature();
        String[] parameterNames = methodSignature.getParameterNames();
        Object[] args = point.getArgs();
        int i = 0;
        List<String> paramList = new ArrayList<>();
        for (Object pojo : args) {
            if (pojo instanceof HttpServletRequest || pojo instanceof HttpServletResponse) {
                continue;
            }
            String e = parameterNames[i++] + ":" + JSON.toJSONString(pojo);
            paramList.add(e);
        }
        return String.format("[%s]", String.join(",", paramList));
    }

}
